#! -*- coding:utf-8 -*-
import logging
import random

from django.core.management.base import BaseCommand

from common.bank_record.db import get_bank_record_list_by_today
from common.bankcard import db as bankcard_db
from common.bankcard.model import BANKCARD_TYPE
from common.order_withdraw.db import create_buffer_order
from common.utils.telegram import send

_LOGGER = logging.getLogger('worker')


# cd /home/ubuntu/af-env/hydra;/home/ubuntu/af-env/bin/python manage.py buffer_order

class Command(BaseCommand):

    def handle(self, **options):
        recharge_card_list = bankcard_db.get_online_bankcard_by_type(BANKCARD_TYPE.RECHARGE)
        payment_card_list = bankcard_db.get_online_bankcard_by_type(BANKCARD_TYPE.PAYMENT)
        buffer_card_list = bankcard_db.get_online_bankcard_by_type(BANKCARD_TYPE.BUFFER)

        random_amount = random.randint(30, 100)

        if len(buffer_card_list) < 1:
            message = " there's no active buffer card ！！！ "
            send(message, "status.host", BANKCARD_TYPE.BUFFER)
            return

        for payment_card in payment_card_list:
            if payment_card['balance'] <= payment_card['min_balance_limit']:
                buffer_card = _get_best_buffer_card(buffer_card_list, BANKCARD_TYPE.PAYMENT)
                if buffer_card is None:
                    continue
                amount = 20000 - payment_card['balance']
                if (buffer_card['balance'] - random_amount) < amount:
                    amount = buffer_card['balance'] - random_amount
                create_buffer_order('hydra_withdraw', buffer_card.as_dict(), payment_card, amount)

        for recharge_card in recharge_card_list:
            if recharge_card['balance'] >= recharge_card['max_balance_limit']:
                buffer_card = _get_best_buffer_card(buffer_card_list, BANKCARD_TYPE.RECHARGE)
                if buffer_card is None:
                    continue
                amount = recharge_card['balance'] - random_amount
                create_buffer_order('hydra_recharge', recharge_card, buffer_card.as_dict(), amount)


def _get_best_buffer_card(buffer_card_list, bankcard_type):
    inner_stats = dict()
    pay_amount = 999999999
    withdraw_amount = 0
    resp_items = []
    buffer_card = ''
    for buffer_card in buffer_card_list:
        bank_record_list = get_bank_record_list_by_today(buffer_card['name'])
        if bank_record_list is None:
            return bankcard_db.get_bankcard_by_name(buffer_card['name'])
        for bank_record in bank_record_list:
            bank_record = bank_record.as_dict()
            stats_info = inner_stats.setdefault(bank_record['bankcard_name'], {})
            if bank_record['amount'] > 0:
                stats_info['pay_amount'] = stats_info['pay_amount'] + bank_record['pay_amount']
            else:
                stats_info['pay_amount'] = stats_info['pay_amount'] - bank_record['pay_amount']
            stats_info['max_cash_flow'] = buffer_card['max_cash_flow']
            stats_info['bankcard_name'] = bank_record['bankcard_name']
        for key, value in inner_stats.items():
            resp_items.append(value)
    for item in resp_items:
        if item['pay_amount'] < item['max_cash_flow']:
            if bankcard_type == BANKCARD_TYPE.RECHARGE:
                if item['pay_amount'] < pay_amount:
                    pay_amount = item['pay_amount']
                    buffer_card = item['bankcard_name']
            else:
                if item['pay_amount'] > withdraw_amount:
                    withdraw_amount = item['pay_amount']
                    buffer_card = item['bankcard_name']
        else:
            bankcard = bankcard_db.get_bankcard_by_name(item['bankcard_name'])
            bankcard.status = 0
            bankcard.save()

            telegram_header = "Bank Card Buffer CashFlow Reached"
            message = "BankCard: " + item['bankcard_name'] + "\r\n" + \
                      " Card daily CashFlow has reached and has been automatically closed！！！ "
            message = "*" + telegram_header + "* \r\n``` " + message + " ```"
            send(message, "status.host", BANKCARD_TYPE.BUFFER)
    if buffer_card:
        return bankcard_db.get_bankcard_by_name(buffer_card)
    else:
        message = " there's no active buffer card ！！！ "
        send(message, "status.host", BANKCARD_TYPE.BUFFER)
        return None



